package com.qding.park.manager.service.core.biz;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.qding.park.common.core.cache.service.CacheServiceFacade;
import com.qding.park.common.core.exceptions.BaseException;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.adapter.AdapterException;
import com.qding.park.common.core.exceptions.business.manager.adapterfactory.AdapterProxyCreateFail;
import com.qding.park.common.core.exceptions.business.manager.service.ServiceCoreException;
import com.qding.park.common.core.exceptions.business.payment.PaymentException;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.common.utils.ListUtil;
import com.qding.park.common.utils.OrderNumUtil;
import com.qding.park.manager.adapter.factory.AdapterParkProxyFactory;
import com.qding.park.manager.cache.ConfigDataCacheInter;
import com.qding.park.manager.cache.ParkCacheInter;
import com.qding.park.manager.payment.PaymentInterfaceServiec;
import com.qding.park.manager.pojo.ReserveParams;
import com.qding.park.manager.pojo.TbCar;
import com.qding.park.manager.pojo.TbFeetrade;
import com.qding.park.manager.pojo.TbParkspace;
import com.qding.park.manager.pojo.TbReserve;
import com.qding.park.manager.pojo.TbUserInfo;
import com.qding.park.manager.pojo.ap.ApReservationInReminder;
import com.qding.park.manager.pojo.ap.ApReserveOrder;
import com.qding.park.manager.pojo.ap.ApUserCarInfo;
import com.qding.park.manager.pojo.enums.CardTypeEnum;
import com.qding.park.manager.pojo.enums.OrderServiceType;
import com.qding.park.manager.pojo.enums.OrderSourceEnum;
import com.qding.park.manager.pojo.enums.RecordStatusEnum;
import com.qding.park.manager.pojo.enums.ReserverStatusEnum;
import com.qding.park.manager.pojo.enums.ReserverTypeEnum;
import com.qding.park.manager.pojo.enums.UserTypeEnum;
import com.qding.park.manager.pojo.payment.AbstractResult;
import com.qding.park.manager.pojo.payment.OrderParameter;
import com.qding.park.manager.pojo.payment.ResultCreateorder;
import com.qding.park.manager.service.core.config.ParkTempStopNumReserve;
import com.qding.park.manager.service.core.mapper.TbCarMapper;
import com.qding.park.manager.service.core.mapper.TbFeetradeMapper;
import com.qding.park.manager.service.core.mapper.TbInoutRecordMapper;
import com.qding.park.manager.service.core.mapper.TbParkspaceMapper;
import com.qding.park.manager.service.core.mapper.TbReserveMapper;
import com.qding.park.manager.service.core.mapper.TbUserInfoMapper;
import com.qding.park.manager.sms.SmsInterfaceServiec;
import com.qding.park.target.common.adapter.CarAdapter;
import com.qding.park.target.common.adapter.ParkAdapter;
import com.qding.park.target.common.adapter.ReserveAdapter;
import com.qding.park.target.common.entity.AdCarInfo;
import com.qding.park.target.common.entity.AdParkInfo;

@Component("reserveBiz")
public class ReserveBiz {
	private static final Log _log = LogFactory.getLog(ReserveBiz.class);
	@Autowired
	private TbReserveMapper tbReserveMapper;

	@Autowired
	private InoutcheckBiz inoutcheckBiz;
	
	@Autowired
	private TbCarMapper  tbCarMapper;
	
	@Autowired
	private TbUserInfoMapper tbUserInfoMapper;

	@Autowired
	private TbParkspaceMapper tbParkspaceMapper;

	@Autowired
	private AdapterParkProxyFactory adapterParkProxyFactory;

	/**
	 * @Field @tbFeetradeMapper : TODO(资源流水保存)
	 */
	@Autowired
	private TbFeetradeMapper tbFeetradeMapper;

	@Autowired
	private TbInoutRecordMapper tbInoutRecordMapper;

	@Autowired
	private PaymentInterfaceServiec paymentInterfaceServiec;

	@Autowired
	private CacheServiceFacade cacheServiceFacade;

	@Autowired
	private SmsInterfaceServiec smsInterfaceServiec;

	@Autowired
	private ConfigDataCacheInter configDataCacheInter;
	
	@Autowired
	private  ParkCacheInter  parkCacheInter;

	/**
	 * reservePayed(预定单支付成功)
	 *
	 * @Title: reservePayed @Description: TODO @param @param tbReserve
	 * 设定文件 @return void 返回类型 @throws
	 */
	@Transactional(rollbackFor = Throwable.class)
	public void reservePayedHandle(TbReserve tbReserve) throws BaseException {
		TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(tbReserve.getParkID());
		Date now = new Date();
		Date endTime = tbReserve.getEndTime();

		if (now.getTime() > endTime.getTime()) {
			// 已经超时 支付成功下发失败 退款
			tbReserve.setStatus(ReserverStatusEnum.RESERVER_ISSUED_PARKFail.getStatus());
			// 支付成功超时
			int num = tbReserveMapper.timeout_payed(tbReserve);

			if (num == 0) {
				return;
			}
			String carpassId = tbReserve.getBjOrderId();
			paymentInterfaceServiec.refundOrder(carpassId);

		} else {
			tbReserve.setStatus(ReserverStatusEnum.RESERVER_ISSUED_PARKSUCCESS.getStatus());
			// 没有超时
			int num = tbReserveMapper.reservePayedHandle(tbReserve);
			if (num == 0) {
				return;
			}
			/**** 下发预定单 ********/
			ReserveAdapter adapterProxy = adapterParkProxyFactory
					.getReserveAdapter(String.valueOf(tbParkspace.getSupplierId()));
			ApReserveOrder apReserveOrder = new ApReserveOrder();
			apReserveOrder.setParkId(tbParkspace.getParkCode());
			apReserveOrder.setCarNum(tbReserve.getCarNum());
			apReserveOrder.setStartTime(tbReserve.getStartTime());
			apReserveOrder.setEndTime(tbReserve.getEndTime());
			apReserveOrder.setOrderId(tbReserve.getParkOrderId());
			adapterProxy.reserveParkSpace(apReserveOrder);
			/**** 下发预定单 ********/
		}

	}

	@Transactional(rollbackFor = Throwable.class)
	public int reserveParkSpace(TbReserve res) throws BaseException {
		String reserveId = res.getId();
		TbReserve tbReserve = tbReserveMapper.queryReservesInfoById(reserveId);

		// TbParkspace tbParkspace =
		// tbParkspaceMapper.queryParkInfoByParkId(tbReserve.getParkID());
		TbParkspace tbParkspace = configDataCacheInter.queryParkSpace(tbReserve.getParkID());
		/**** 下发预定单 ********/
		ReserveAdapter adapterProxy = adapterParkProxyFactory
				.getReserveAdapter(String.valueOf(tbParkspace.getSupplierId()));
		ApReserveOrder apReserveOrder = new ApReserveOrder();
		apReserveOrder.setParkId(tbParkspace.getParkCode());
		apReserveOrder.setCarNum(tbReserve.getCarNum());
		apReserveOrder.setStartTime(tbReserve.getStartTime());
		apReserveOrder.setEndTime(tbReserve.getLastTime());
		apReserveOrder.setOrderId(tbReserve.getParkOrderId());
		adapterProxy.reserveParkSpace(apReserveOrder);
		/**** 下发预定单 ********/

		tbReserve.setStatus(ReserverStatusEnum.RESERVER_ISSUED_PARKSUCCESS.getStatus());
		// 下发完成指令更新
		int num = tbReserveMapper.parkIssued(tbReserve);
		return num;
		// if(num==1){
		// /*********** 加入监控列表 ***************************/
		// cacheServiceFacade.reserve_monitor_add(tbReserve);
		// /*********** 加入监控列表 ***************************/
		// }

	}

	@Transactional(rollbackFor = Throwable.class)
	public void createReserveOrder(TbReserve tbReserve) throws BaseException {
		String carNum = tbReserve.getCarNum();
		String bjuserid = tbReserve.getBjuserId();
		TbUserInfo tbUserInfo = tbUserInfoMapper.queryUseByBjuseridType(bjuserid, UserTypeEnum.REGISTER_USER.getType());

		if (tbUserInfo == null) {
			// 没有此用户
			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getId(), null,
					ExceptionMessage.createExceptionMessage(
							ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getDesc(), "没有此用户",
							"bjuserid=" + bjuserid));
		}
		
		TbCar  car=tbCarMapper.queryCarOfParkByParkIdUserIdCarNum(tbReserve.getParkID(), tbUserInfo.getId(), carNum);
		if(car==null){
			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getId(), null,
					ExceptionMessage.createExceptionMessage(
							ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getDesc(), "车辆未在该项目登记，不支持预约",
							"carNum=" + carNum));
		}
		
		List<TbReserve> resList = tbReserveMapper.listByCarnum(carNum);
		if (!ListUtil.isEmpty(resList)) {
			// 车辆已经预定了
			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_CAR_RESERVED.getId(), null,
					ExceptionMessage.createExceptionMessage(
							ServiceCoreException.TypeEnum.EXCEPTION_CAR_RESERVED.getDesc(), "该车辆已预约过车位，请勿重复预约",
							"carNum=" + carNum));
		}

		if (inoutcheckBiz.isPresence(tbReserve.getParkID(), carNum)) {
			// 车辆已入场 不能再预定
			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_INCHECKED_CAR.getId(), null,
					ExceptionMessage.createExceptionMessage(
							ServiceCoreException.TypeEnum.EXCEPTION_INCHECKED_CAR.getDesc(), "车辆已进场，不支持预约",
							"carNum=" + carNum));
		}
		
		/********* 检查卡片属性 ***************/
		TbCar tbCar=tbCarMapper.queryCarOfParkByParkIdUserIdCarNum(tbReserve.getParkID(), tbUserInfo.getId(), carNum);
		TbParkspace tbParkspace = configDataCacheInter.queryParkSpace(tbReserve.getParkID());
		int supplierId = tbParkspace.getSupplierId();
		String parkCode = tbParkspace.getParkCode();
		CarAdapter adapterProxy = adapterParkProxyFactory.getCarAdapter(String.valueOf(supplierId));
		AdCarInfo  apUserCarInfo=adapterProxy.getMonthCardInfo(parkCode, carNum);
		if(CardTypeEnum.VIP_TYPE.getType()==tbCar.getCardType()||"vip卡".equals(apUserCarInfo.getCardDescript())){
			//属于vip卡
			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_CAR_RESERVED.getId(), null,
					ExceptionMessage.createExceptionMessage(
							ServiceCoreException.TypeEnum.EXCEPTION_CAR_RESERVED.getDesc(), "该车牌属于固定车位，不支持车位预定",
							"carNum=" + carNum));
		}
		/********* 检查卡片属性 ***************/
		
		/********* 检查车位数 ***************/
		ParkAdapter parkAdapter = adapterParkProxyFactory.getParkAdapter(String.valueOf(supplierId));
		AdParkInfo parkInfo= parkAdapter.getTempStopNum(parkCode,"");
		int stopNum =parkInfo.getRestSpace();
		if (stopNum - ParkTempStopNumReserve.getPark_tempStopNum_reserve() <= 0) {
			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_STOPSPACE.getId(), null,
					ExceptionMessage.createExceptionMessage(
							ServiceCoreException.TypeEnum.EXCEPTION_NO_STOPSPACE.getDesc(), "没有车位，不能预定",
							"carNum=" + carNum));
		}
		/********* 检查车位数 **************/

		int deferred_Reservation = tbParkspace.getDeferred_Reservation();
		int userId = tbUserInfo.getId();
		tbReserve.setId(OrderNumUtil.getOrderNum(userId,OrderServiceType.RESERVER.getTag()));
		String parkName = tbParkspace.getName();
		tbReserve.setParkName(parkName);
		int reserveTime = tbParkspace.getReserveTime();

		Date startTime = tbReserve.getStartTime();
		tbReserve.setDeposit(tbParkspace.getReservedeposit());
		// 预定结束时间
		tbReserve.setEndTime(DateUtils.addMinute(startTime, reserveTime));
		// 预定失效时间
		// tbReserve.setLastTime(DateUtils.addMinute(tbReserve.getEndTime(),
		// deferred_Reservation));
		tbReserve.setUserID(tbUserInfo.getId());
		tbReserve.setReserverType(ReserverTypeEnum.RESERVER.getType());
		tbReserve.setStatus(ReserverStatusEnum.RESERVER_ORDER_ININT.getStatus());

		int orderType = OrderParameter.OrderTypeEnum.RESERVER_TYPE.getType();
		int totalPrice = tbReserve.getDeposit();
		int orderSource = OrderSourceEnum.APP.getType();
		String szCarpassId = tbReserve.getId();
		String memberId = tbReserve.getBjuserId();
		OrderParameter orderparameter = new OrderParameter();
		orderparameter.setOrderType(orderType);
		orderparameter.setTotalPrice(totalPrice);
		orderparameter.setOrderSource(orderSource);
		orderparameter.setSzCarpassId(szCarpassId);
		orderparameter.setMemberId(memberId);
		orderparameter.setProjectId(tbParkspace.getBjprojectId());

		ResultCreateorder resultCreateorder = paymentInterfaceServiec.createOrder(orderparameter);
		if (resultCreateorder.getCode() != AbstractResult.ResultCodeEnum.SUCESS.getCode()) {
			throw new PaymentException(PaymentException.TypeEnum.EXCEPTION_PAYMENT_FAIL.getId(), null,
					ExceptionMessage.createExceptionMessage(PaymentException.TypeEnum.EXCEPTION_PAYMENT_FAIL.getDesc(),
							"创建订单失败:payPlatform:" + resultCreateorder.getMessage(),
							" orderType=" + orderType + ",totalPrice=" + totalPrice + ",orderSource" + orderSource
									+ ",szCarpassId=" + szCarpassId + ",memberId=" + memberId + ",orderId" + memberId));
		}

		tbReserve.setBjOrderId(resultCreateorder.getOrderId());
		tbReserve.setParkOrderId(tbReserve.getId());
		tbReserve.setOrderSource(orderSource);
		int num = tbReserveMapper.save(tbReserve);
		if (num == 0) {
			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_CAR_RESERVED.getId(), null,
					ExceptionMessage.createExceptionMessage(
							ServiceCoreException.TypeEnum.EXCEPTION_CAR_RESERVED.getDesc(), "该车辆已预约过车位，请勿重复预约",
							"carNum=" + carNum));
		}

	}

	/**
	 * queryReserveParams(根据车场id 查询车场的预定规则)
	 *
	 * @Title: queryReserveParams @Description: TODO @param @param
	 * parkId @param @return 设定文件 @return ReserveParams 返回类型 @throws
	 */
	public ReserveParams queryReserveParams(int parkId) {

		ReserveParams params = tbReserveMapper.reserveParams(parkId);
		return params;
	}

	/**
	 * setReserveParams(设置预定参数) TODO(这里描述这个方法适用条件 – 可选) TODO(这里描述这个方法的执行流程 – 可选)
	 * TODO(这里描述这个方法的使用方法 – 可选) TODO(这里描述这个方法的注意事项 – 可选)
	 *
	 * @Title: setReserveParams @Description: TODO @param @param
	 * params @param @param parkId 设定文件 @return void 返回类型 @throws
	 */
	public void setReserveParams(ReserveParams params, int parkId) {
		tbReserveMapper.updateReserveParams(params, parkId);
		parkCacheInter.clear(parkId);
	}

	// /**
	// * @throws AdapterException @Title: reserveParkSpace @Description:
	// * TODO(生成预定单 返回预定单号) @param @param tbReserve @param @return @param
	// @throws
	// * ServiceCoreException @param @throws AdapterProxyCreateFail 参数 @return
	// int
	// * 返回类型 @throws
	// * @throws NetWorkException
	// */
	// @Transactional(rollbackFor=Throwable.class)
	// public String reserveParkSpace(TbReserve tbReserve)
	// throws ServiceCoreException, AdapterProxyCreateFail, AdapterException,
	// NetWorkException {
	//
	// String bjuserid = tbReserve.getBjuserId();
	//
	// String carNum = tbReserve.getCarNum();
	//
	// TbUserInfo tbUserInfo = tbUserInfoMapper.queryUserByBjUserId(bjuserid);
	//
	// if (tbUserInfo == null) {
	// throw new
	// ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NOFIND_USER.getId(),
	// null,
	// ExceptionMessage.createExceptionMessage(
	// ServiceCoreException.TypeEnum.EXCEPTION_NOFIND_USER.getDesc(), "没有此用户",
	// "bjuserid=" + bjuserid));
	// }
	//
	// List<TbReserve> resList = tbReserveMapper.listByCarnum(carNum);
	// if (!ListUtil.isEmpty(resList)) {
	// // 车辆已经预定了
	// throw new
	// ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_CAR_RESERVED.getId(),
	// null,
	// ExceptionMessage.createExceptionMessage(
	// ServiceCoreException.TypeEnum.EXCEPTION_CAR_RESERVED.getDesc(),
	// "该车辆已预约过车位，请勿重复预约",
	// "carNum=" + carNum));
	// }
	//
	//
	//// List<TbInoutRecord> inCheckList
	// =tbInoutRecordMapper.queryIncheckByCarPark(tbReserve.getParkID(),carNum);
	//// if(!ListUtil.isEmpty(inCheckList)){
	// if(inoutcheckBiz.isPresence(tbReserve.getParkID(),carNum)){
	// //车辆已入场 不能再预定
	// throw new
	// ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_INCHECKED_CAR.getId(),
	// null,
	// ExceptionMessage.createExceptionMessage(
	// ServiceCoreException.TypeEnum.EXCEPTION_INCHECKED_CAR.getDesc(),
	// "车辆已进场，不支持预约",
	// "carNum=" + carNum));
	// }
	//// }
	//
	//
	// TbParkspace tbParkspace =
	// tbParkspaceMapper.queryParkInfoByParkId(tbReserve.getParkID());
	// int supplierId = tbParkspace.getSupplierId();
	// String parkCode = tbParkspace.getParkCode();
	// /*********检查车位数***************/
	// AdapterProxy adapterProxy =
	// adapterParkProxyFactory.createAdapterParkProxyBySupplierId(supplierId);
	// int stopNum=adapterProxy.getParkAdapter().getTempStopNum(parkCode);
	// if(stopNum-SystemConfig.park_tempStopNum_reserve<=0){
	// throw new
	// ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_STOPSPACE.getId(),
	// null,
	// ExceptionMessage.createExceptionMessage(
	// ServiceCoreException.TypeEnum.EXCEPTION_NO_STOPSPACE.getDesc(),
	// "没有车位，不能预定",
	// "carNum=" + carNum));
	// }
	// /*********检查车位数**************/
	// int deferred_Reservation=tbParkspace.getDeferred_Reservation();
	// int userId = tbUserInfo.getId();
	// tbReserve.setId(OrderNumUtil.getOrderNum(userId));
	// String parkName = tbParkspace.getName();
	// tbReserve.setParkName(parkName);
	// int reserveTime = tbParkspace.getReserveTime();
	//
	// Date startTime = tbReserve.getStartTime();
	// //预定结束时间
	// tbReserve.setEndTime(DateUtils.addMinute(startTime, reserveTime));
	// //预定失效时间
	// tbReserve.setLastTime(DateUtils.addMinute(tbReserve.getEndTime(),
	// deferred_Reservation));
	// tbReserve.setUserID(tbUserInfo.getId());
	// tbReserve.setReserverType(ReserverTypeEnum.RESERVER.getType());
	// tbReserve.setStatus(ReserverStatusEnum.RESERVER_NON_INCHECK.getStatus());
	// int num = tbReserveMapper.save(tbReserve);
	// if(num==0){
	// throw new
	// ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_CAR_RESERVED.getId(),
	// null,
	// ExceptionMessage.createExceptionMessage(
	// ServiceCoreException.TypeEnum.EXCEPTION_CAR_RESERVED.getDesc(),
	// "该车辆已预约过车位，请勿重复预约",
	// "carNum=" + carNum));
	// }
	// String orderId = tbReserve.getId();
	//
	//// Date endTime = DateUtils.addMinute(startTime, 30);
	// /**** 下发预定单 ********/
	//// AdapterProxy adapterProxy =
	// adapterParkProxyFactory.createAdapterParkProxyBySupplierId(supplierId);
	// ApReserveOrder apReserveOrder = new ApReserveOrder();
	// apReserveOrder.setParkId(parkCode);
	// apReserveOrder.setCarNum(carNum);
	// apReserveOrder.setStartTime(startTime);
	// apReserveOrder.setEndTime(tbReserve.getLastTime());
	// apReserveOrder.setOrderId(orderId);
	// adapterProxy.getReserveAdapter().reserveParkSpace(apReserveOrder);
	// /**** 下发预定单 ********/
	//
	// return tbReserve.getId();
	//
	// // return reserve.getId();
	// }

	public List<TbReserve> queryReservesByBjuserId(String bjuserid) throws ServiceCoreException {

		// TbUserInfo tbUserInfo =
		// tbUserInfoMapper.queryUserByBjUserId(bjuserid);
		TbUserInfo tbUserInfo = tbUserInfoMapper.queryUseByBjuseridType(bjuserid, UserTypeEnum.REGISTER_USER.getType());

		if (tbUserInfo == null) {
			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NOFIND_USER.getId(), null,
					ExceptionMessage.createExceptionMessage(
							ServiceCoreException.TypeEnum.EXCEPTION_NOFIND_USER.getDesc(), "", "bjuserid=" + bjuserid));
		}
		int userId = tbUserInfo.getId();
		List<TbReserve> list = tbReserveMapper.listByUserId(userId);

		return list;

	}

	public TbReserve queryReservesInfoById(String reserveId) {

		return tbReserveMapper.queryReservesInfoById(reserveId);

	}

	@Transactional(rollbackFor = Throwable.class)
	public int cancelReservesById(String reserveId) throws AdapterProxyCreateFail, AdapterException {
		TbReserve tbReserve = tbReserveMapper.queryReservesInfoById(reserveId);
		int parkId = tbReserve.getParkID();
		String carNum = tbReserve.getCarNum();
		tbReserve.setStatus(ReserverStatusEnum.RESERVER_CANCEL.getStatus());
		int num = tbReserveMapper.cancelReserves(tbReserve);
		if (num == 0) {
			return num;
		}
		/**** 下发取消预定单 ********/
		TbParkspace tbParkspace = configDataCacheInter.queryParkSpace(parkId);
		int supplierId = tbParkspace.getSupplierId();
		String parkCode = tbParkspace.getParkCode();
		ReserveAdapter adapterProxy = adapterParkProxyFactory.getReserveAdapter(String.valueOf(supplierId));
		ApReserveOrder apReserveOrder = new ApReserveOrder();
		apReserveOrder.setParkId(parkCode);
		apReserveOrder.setCarNum(carNum);
		apReserveOrder.setStartTime(tbReserve.getStartTime());
		apReserveOrder.setEndTime(tbReserve.getEndTime());
		apReserveOrder.setOrderId(reserveId);
		adapterProxy.cancelReserve(apReserveOrder);
		/**** 下发取消预定单 ********/
		
		/**** *此处要调用北京接口 ********/
		// 退款押金
		TbFeetrade tbFeetrade = new TbFeetrade();
		tbFeetrade.setId(OrderNumUtil.getOrderNum(tbReserve.getUserID(),OrderServiceType.FEETRADE.getTag()));
		tbFeetrade.setUserID(tbReserve.getUserID());
		tbFeetrade.setParkID(tbReserve.getParkID());
		tbFeetrade.setFeeType(TbFeetrade.FeeTypeEnum.REFUND_PAY.getType());
		tbFeetrade.setFeeCost(tbReserve.getDeposit());
		tbFeetrade.setBusinessID(tbReserve.getTradeid());
		tbFeetrade.setChannel(TbFeetrade.ChannelEnum.CAPITALFLOW_ONLINE.getType());
		tbFeetrade.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
		tbFeetradeMapper.save(tbFeetrade);
		/**** 调用北京接口 *****/
		// 没有超时 退还押金
		paymentInterfaceServiec.refundOrder(tbReserve.getId());
		/**** 调用北京接口 *****/
		return num;
	}

	/**
	 * @Description (查询所属预定
	 * @param supplyID
	 * @param parkCode
	 * @param carNum
	 * @return
	 */
	public TbReserve queryReservedByBjuserId(int supplyID, String parkCode, String carNum) {
		TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByCodeSupplier(parkCode, supplyID);
		int parkId = tbParkspace.getId();

		return tbReserveMapper.queryReservedByParkCarnum(parkId, carNum);
	}

	@Transactional(rollbackFor = Throwable.class)
	public void carInCheck(ApReservationInReminder apReservationInReminder) throws BaseException {
		// 卡号
		String cardCode = apReservationInReminder.getCardCode();
		// 车牌
		String carNum = apReservationInReminder.getCarNum();
		// 进场时间
		Date inDateTime = apReservationInReminder.getInDateTime();
		// 进场侬岗
		String inRoom = apReservationInReminder.getInRoom();
		// 车场编号
		String parkCode = apReservationInReminder.getParkId();
		// 车场供应闪编号
		String supplyID = apReservationInReminder.getSupplyID();
		TbParkspace tbParkspace = configDataCacheInter.queryParkSpace(parkCode, Integer.valueOf(supplyID));
		int parkId = tbParkspace.getId();
		TbReserve tbReserve = tbReserveMapper.queryReservedByParkCarnum(parkId, carNum);
		
		if(tbReserve==null){
			_log.error("没有找到此预定");
			return ;
		}
		/**** 计算是否超时进场 ********/
		boolean istimout = false;
		String reserveId = tbReserve.getId();
		istimout = new Date().getTime() > tbReserve.getEndTime().getTime() ? true : false;
		/************/

		if (istimout) {
			// 超时进场
			/***************/
			tbReserve.setStatus(ReserverStatusEnum.RESERVER_OVERTIME_INCHECK.getStatus());
			tbReserve.setCheckInTime(inDateTime);
			int num = tbReserveMapper.timeoutIncheck(tbReserve);
			if (num == 0) {
				_log.error("无效的预定:" + tbReserve);
				return;
			}
			/**** 下发取消预定单 ********/
			int supplierId = tbParkspace.getSupplierId();
			ReserveAdapter adapterProxy = adapterParkProxyFactory.getReserveAdapter(String.valueOf(supplierId));
			ApReserveOrder apReserveOrder = new ApReserveOrder();
			apReserveOrder.setParkId(parkCode);
			apReserveOrder.setCarNum(tbReserve.getCarNum());
			apReserveOrder.setStartTime(tbReserve.getStartTime());
			apReserveOrder.setEndTime(tbReserve.getEndTime());
			apReserveOrder.setOrderId(reserveId);
			adapterProxy.cancelReserve(apReserveOrder);
			/**** 下发取消预定单 ********/
		} else {
			// 没有超时
			tbReserve.setStatus(ReserverStatusEnum.RESERVER_INCHECK.getStatus());
			tbReserve.setCheckInTime(inDateTime);
			int num = tbReserveMapper.incheck(tbReserve);

			if (num == 0) {
				_log.error("无效的预定:" + tbReserve);
				return;
			}

			/**** 下发取消预定单 ********/
//			TbParkspace tbParkspace = configDataCacheInter.queryParkSpace(tbReserve.getParkID());
//			String parkCode = tbParkspace.getParkCode();
			int supplierId = tbParkspace.getSupplierId();
			ReserveAdapter adapterProxy = adapterParkProxyFactory.getReserveAdapter(String.valueOf(supplierId));
			ApReserveOrder apReserveOrder = new ApReserveOrder();
			apReserveOrder.setParkId(parkCode);
			apReserveOrder.setCarNum(tbReserve.getCarNum());
			apReserveOrder.setStartTime(tbReserve.getStartTime());
			apReserveOrder.setEndTime(tbReserve.getEndTime());
			apReserveOrder.setOrderId(reserveId);
			adapterProxy.cancelReserve(apReserveOrder);
			/**** 下发取消预定单 ********/

			/**** *此处要调用北京接口 ********/
			// 退款押金
			TbFeetrade tbFeetrade = new TbFeetrade();
			tbFeetrade.setId(OrderNumUtil.getOrderNum(tbReserve.getUserID(),OrderServiceType.FEETRADE.getTag()));
			tbFeetrade.setUserID(tbReserve.getUserID());
			tbFeetrade.setParkID(tbReserve.getParkID());
			tbFeetrade.setFeeType(TbFeetrade.FeeTypeEnum.REFUND_PAY.getType());
			tbFeetrade.setFeeCost(tbReserve.getDeposit());
			tbFeetrade.setBusinessID(tbReserve.getTradeid());
			tbFeetrade.setChannel(TbFeetrade.ChannelEnum.CAPITALFLOW_ONLINE.getType());
			tbFeetrade.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
			tbFeetradeMapper.save(tbFeetrade);
			/**** 调用北京接口 *****/
			// 没有超时 退还押金
			paymentInterfaceServiec.refundOrder(tbReserve.getId());
			/**** 调用北京接口 *****/
		}

	}

	/**
	 * reserveTimeOut(预定超时)
	 *
	 * @Title: reserveTimeOut @Description: TODO @param @param
	 * reserve @param @throws AdapterProxyCreateFail @param @throws
	 * AdapterException 设定文件 @return void 返回类型 @throws
	 */
	@Transactional(rollbackFor = Throwable.class)
	public void reserveTimeOut(TbReserve reserve) throws AdapterProxyCreateFail, AdapterException {
		String id = reserve.getId();
		int userId = reserve.getUserID();
		int num = tbReserveMapper.updateStatusTimeout(id, ReserverStatusEnum.RESERVER_OVERTIME.getStatus());

		if (num == 0) {
			_log.error("id:" + id + " 数据不一致性");
//			return;
		}

		// TbReserve tbReserve=tbReserveMapper.queryReservesInfoById(id);
		TbUserInfo tbuserinfo = tbUserInfoMapper.userInfoById(userId);
		/****** 下发取消息预定单 ****************/
		TbParkspace tbParkspace = configDataCacheInter.queryParkSpace(reserve.getParkID());
		int supplierId = tbParkspace.getSupplierId();
		String parkCode = tbParkspace.getParkCode();
		ReserveAdapter adapterProxy = adapterParkProxyFactory.getReserveAdapter(String.valueOf(supplierId));
		ApReserveOrder apReserveOrder = new ApReserveOrder();
		apReserveOrder.setParkId(parkCode);
		apReserveOrder.setCarNum(reserve.getCarNum());
		apReserveOrder.setStartTime(reserve.getStartTime());
		apReserveOrder.setEndTime(reserve.getEndTime());
		apReserveOrder.setOrderId(id);
		adapterProxy.cancelReserve(apReserveOrder);
		/****** 下发取消息预定单 ****************/

		/****** 向用户发送 预定单超时消息 *************/
//		ReserveDepositNotice notice = new ReserveDepositNotice();
//		notice.setMobile(String.valueOf(tbuserinfo.getTel()));
//		notice.setExtendTimeNum(reserve.getExtendTimeNum());
//		notice.setCancelTimePoint(reserve.getLastTime());
//		smsInterfaceServiec.reserve_deposit_notice(notice);
		smsInterfaceServiec.reserve_timeout_notice(String.valueOf(tbuserinfo.getTel()));
		/****** 向用户发送 预定单超时 *************/
	}

	public void reserveDelayTimeOut(TbReserve reserve) throws BaseException {
		String id = reserve.getId();
		int userId = reserve.getUserID();
		int num = tbReserveMapper.updateStatusTimeout(id, ReserverStatusEnum.RESERVER_DELAY_TIMEOUT.getStatus());

		if (num == 0) {
			_log.error("id:" + id + " 数据不一致性");
			return;
		}
		TbUserInfo tbuserinfo = tbUserInfoMapper.userInfoById(userId);

		/****** 下发取消息预定单 ****************/
		TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(reserve.getParkID());
		int supplierId = tbParkspace.getSupplierId();
		String parkCode = tbParkspace.getParkCode();
		ReserveAdapter adapterProxy = adapterParkProxyFactory.getReserveAdapter(String.valueOf(supplierId));
		ApReserveOrder apReserveOrder = new ApReserveOrder();
		apReserveOrder.setParkId(parkCode);
		apReserveOrder.setCarNum(reserve.getCarNum());
		apReserveOrder.setStartTime(reserve.getStartTime());
		apReserveOrder.setEndTime(reserve.getEndTime());
		apReserveOrder.setOrderId(id);
		adapterProxy.cancelReserve(apReserveOrder);
		/****** 下发取消息预定单 ****************/

		/****** 向用户发送 预定单延期超时消息 *************/
		smsInterfaceServiec.reserve_timeout_notice(String.valueOf(tbuserinfo.getTel()));
		/****** 向用户发送 预定单延期超时 *************/
	}
	
	/**
	 * @param reserve
	 *            预定单
	 * @return 得到当前预定状态
	 */
	public String getCurrentStatus(TbReserve reserve) {

		if (reserve.getStatus() == ReserverStatusEnum.RESERVER_PAYED_SUCCESS.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_ISSUED_PARKSUCCESS.getStatus()

		) {

			return "待进场";
		} else if (reserve.getStatus() == ReserverStatusEnum.RESERVER_INCHECK.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_DELAY_TIMEOUT.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_OVERTIME_INCHECK.getStatus()) {

			String checkInTimeStr = reserve.getCheckInTime() == null ? ""
					: DateUtils.formatDate(reserve.getCheckInTime(), DateUtils.DATE_FORMAT_DATETIME);
			return checkInTimeStr + " 已入场";
		} else if (reserve.getStatus() == ReserverStatusEnum.RESERVER_CANCEL.getStatus()
//				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_OVERTIME.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_ISSUED_PARKFail.getStatus()) {
			String timeStr = reserve.getUpdate_date() == null ? ""
					: DateUtils.formatDate(reserve.getUpdate_date(), DateUtils.DATE_FORMAT_DATETIME);
			return timeStr+" 已取消";
		}else if(reserve.getStatus() == ReserverStatusEnum.RESERVER_OVERTIME.getStatus()){
			String timeStr = reserve.getEndTime() == null ? ""
					: DateUtils.formatDate(reserve.getEndTime(), DateUtils.DATE_FORMAT_DATETIME);
			return timeStr+" 已过期";
		}else if(reserve.getStatus() == ReserverStatusEnum.DEL.getStatus()){
			return "用户端删除";
		}
		
		else {
			return "";
		}
	}

	public int getOrderFee(TbReserve reserve) {
		if (reserve.getStatus() == ReserverStatusEnum.RESERVER_PAYED_SUCCESS.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_INCHECK.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_OVERTIME.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_OVERTIME_INCHECK.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_ISSUED_PARKSUCCESS.getStatus()) {

			return reserve.getDeposit();

		} else {
			return 0;
		}
	}
	
	@Transactional(rollbackFor = Throwable.class)
	public  void issuedFailRollBack(TbReserve tbReserve){
		tbReserve.setStatus(ReserverStatusEnum.RESERVER_ISSUED_PARKFail.getStatus());
		tbReserveMapper.reserveIssuedFailRollBack(tbReserve);
		
		/**** *此处要调用北京接口 ********/
		// 退款押金
		TbFeetrade tbFeetrade = new TbFeetrade();
		tbFeetrade.setId(OrderNumUtil.getOrderNum(tbReserve.getUserID(),OrderServiceType.FEETRADE.getTag()));
		tbFeetrade.setUserID(tbReserve.getUserID());
		tbFeetrade.setParkID(tbReserve.getParkID());
		tbFeetrade.setFeeType(TbFeetrade.FeeTypeEnum.REFUND_PAY.getType());
		tbFeetrade.setFeeCost(tbReserve.getRealPayDeposit());
		tbFeetrade.setBusinessID(tbReserve.getId());
		tbFeetrade.setChannel(TbFeetrade.ChannelEnum.CAPITALFLOW_ONLINE.getType());
		tbFeetrade.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
		tbFeetradeMapper.save(tbFeetrade);
		/**** 调用北京接口 *****/
		// 没有超时 退还押金
		paymentInterfaceServiec.refundOrder(tbReserve.getBjOrderId());
		/**** 调用北京接口 *****/
	}
	
	public String getOrderStatusStr(TbReserve reserve) {
		String temp = null;

		String createTimestr = DateUtils.formatDate(reserve.getCreate_date(), DateUtils.DATE_FORMAT_DATETIME);
		createTimestr = createTimestr + " ";
		String tag = "成功";
		if (reserve.getStatus() == ReserverStatusEnum.RESERVER_PAYED_SUCCESS.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_INCHECK.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_CANCEL.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_OVERTIME.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_OVERTIME_INCHECK.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.RESERVER_ISSUED_PARKSUCCESS.getStatus()
				|| reserve.getStatus() == ReserverStatusEnum.DEL.getStatus()) {
			tag = "成功";
		} else {
			tag = "失败";
		}
		temp = createTimestr + tag;
		return temp;
	}
}
